/* $mibsd: search.c,v 1.2 2005/11/11 00:23:49 dhg Exp $
 *
 * Usage: search [path] file
 *
 */


#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <dirent.h>

#include <string.h>

#include <errno.h>



int schflag = 0;



int isdir(char *);

void search(char *, char *);



main(int argc, char **argv)

{

	char *fname;

	char cbuf[BUFSIZ];

	char *cdir;



	if ( argc == 1) {

		printf("Usage: %s [path] file\n", argv[0]);

		printf("\tif no path is given as a command line argument,\n");

		printf("\tthe current dir is set as the default search dir.\n");

		exit(0);

	}

	if ( argc == 2) {

		fname = argv[1];

		cdir = (char *) getcwd(cbuf, BUFSIZ);

	}

	if( argc == 3) {

		fname = argv[2];

		cdir = argv[1];

	}



	//printf("current dir is %s\n", cdir);

	search(cdir, fname);



	if(!schflag)

		printf("	=====> %s: '%s' not found.\n",argv[0], fname);

}



int

isdir(char *name)

{

	struct stat stbuf;



	if( lstat(name, &stbuf) < 0)  {

		printf("	=====> stat: %s :%s\n",name, strerror(errno));

		return 0;

	}

	else

		return (S_ISDIR(stbuf.st_mode))? 1 : 0 ;

}



void

search(char *path, char *fname)

{

	DIR *dirp;

	struct dirent *dir;

	char buffer[BUFSIZ];





	if(isdir(path)) {

		if( (dirp = opendir(path)) == NULL) {

			printf("	=====> Error opening dir %s", path);

			printf("	=====>  :%s\n", strerror(errno));

			return;

		}

	}

	else 

		return;



	while( (dir = readdir(dirp)) != NULL) {

	  if(!strncmp(dir->d_name, ".", 2) || !strncmp(dir->d_name, "..", 3) ) { }

	else {

		   bzero(buffer, sizeof(buffer));

		   strlcat(buffer, path, sizeof(buffer));

		   if(path[strlen(path) - 1] == '/');

		   else 

			strlcat(buffer, "/", sizeof(buffer));

		   strlcat(buffer, dir->d_name, sizeof(buffer));

		if(isdir(buffer)) {

		   //printf("%s is a dir.\n", buffer);

		   search(buffer, fname);

		}

		else {

	//	printf("%s is NOT a dir.\n", dir->d_name);

	//	printf("%s/%s\n", path, dir->d_name);

		if (dir->d_namlen == strlen(fname) && !strcmp(dir->d_name, fname)) {

				schflag = 1;

				printf("	=====> Found: %s/%s\n", path,fname);

				} 

			}

		}

	}

	closedir(dirp);

}
